package de.tum.in.eist.poll.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import de.tum.in.eist.poll.client.PollService;
import de.tum.in.eist.poll.shared.*;

import java.util.*;


public class PollServiceImp extends RemoteServiceServlet implements PollService {
	private static final long serialVersionUID = -3119867631363519570L;

	public PollServiceImp() {
	}

	/**
	 * The implementation counterpart of {@link PollService#login(String, String)}.
	 */
	public User login(String name, String password)
			throws IllegalArgumentException {
		if (!Database.isValidInput(name, password))
			throw new IllegalArgumentException("Wrong user name or password!");
		else
			return Database.getUser(name);
	}

	/**
	 * The implementation counterpart of {@link PollService#submitFeedback(Feedback feedback)}.
	 */
	public String submitFeedback(Feedback feedback) {
		Lecture lecture = Database.getLecture(feedback.getLecture()
				.getLectureID());
		Student student = (Student) Database.getUser(feedback.getStudent()
				.getName());
		Database.addFeedbackToLecture(lecture, feedback);
		lecture.addStudent(student);
		return "Your submission was successful!";
	}
	
	/**
	 * The implementation counterpart of {@link PollService#requestLectures(User user)}.
	 */
	public List<Lecture> requestLectures(User user) {
		List<Lecture> lectures = new LinkedList<Lecture>(Database.getLectures());
		user = Database.getUser(user.getName());
		if (user instanceof Lecturer) {
			for (Iterator<Lecture> iterator = Database.getLectures().iterator(); iterator
					.hasNext();) {
				Lecture lecture = (Lecture) iterator.next();
				if (lecture.getLecturer() == user)
					lectures.remove(lecture);
			}

		}
		return lectures;
	}

	/**
	 * The implementation counterpart of {@link PollService#requestFeedback(Lecture lecture)}.
	 */
	public List<Feedback> requestFeedback(Lecture lecture) {
		lecture = Database.getLecture(lecture.getLectureID());
		return Database.getFeedback(lecture);
	}

	/**
	 * The implementation counterpart of {@link PollService#requestFeedbackCount(Lecture lecture)}.
	 */
	@Override
	public int requestFeedbackCount(Lecture lecture) {
		List<Feedback> lstFeedback = requestFeedback(lecture);
		if(null==lstFeedback)
			return 0;
		return lstFeedback.size();
	}
}
